﻿using System;
using System.Collections.Generic;


namespace LL.Common
{
    /// <summary>
    /// 可嵌套的条件组合
    /// </summary>
    public class ConditionGroup : IConditionGroup
    {
        private IList<ICondition> _conditions;
        private readonly IConditionGroup _parent;
        private IList<ICondition> List
        {
            get
            {
                return _conditions ?? (_conditions = new List<ICondition>());
            }
        }

        public int Count
        {
            get { return List.Count; }
        }
        public Relation Relation { get; set; }
        public IEnumerable<ICondition> Conditions
        {
            get { return List; }
        }

        public ConditionGroup(IConditionGroup parent)
        {
            _parent = parent;
        }

        public IConditionGroup And(IConditionItem condition)
        {
            List.Add(new Condition(Relation.And, condition));
            return this;
        }
        public IConditionGroup Or(IConditionItem condition)
        {
            List.Add(new Condition(Relation.Or, condition));
            return this;
        }

        public IConditionGroup AndGroup()
        {
            var group = new ConditionGroup(this);
            List.Add(group);
            return group;
        }
        public IConditionGroup AndGroup(IConditionItem condition)
        {
            var group = new ConditionGroup(this);
            group.And(condition);
            List.Add(group);
            return group;
        }
        public IConditionGroup OrGroup()
        {
            var group = new ConditionGroup(this) { Relation = Relation.Or };
            List.Add(group);
            return group;
        }
        public IConditionGroup OrGroup(IConditionItem condition)
        {
            var group = new ConditionGroup(this) { Relation = Relation.Or };
            group.And(condition);
            List.Add(group);
            return group;
        }
        public IConditionGroup EndGroup()
        {
            if (_parent == null)
                throw new InvalidOperationException("已经是最外层");
            return _parent;
        }

    }
}